﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AutoUpdate.cs" company="3po.ru">
//   Author: Alexander Ulitin [support@3po.ru]
//   
//   This file is part of Conusic.
//   
//   Conusic is free software: you can redistribute it and/or modify
//   it under the terms of the GNU General Public License as published by
//   the Free Software Foundation, either version 3 of the License, or
//   (at your option) any later version.
//   
//   Conusic is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//   
//   You should have received a copy of the GNU General Public License
//   along with Conusic.  If not, see http://www.gnu.org/licenses/.
// </copyright>
// <summary>
//   Description of AutoUpdate.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ConusicUI
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Reflection;
    using System.Text.RegularExpressions;
    using System.Windows.Forms;

    using Conusic;
    using Conusic.Properties;

    /// <summary>
    /// Description of AutoUpdate.
    /// </summary>
    public static class AutoUpdate
    {
        #region Constants

        /// <summary>
        /// Check updates every day
        /// </summary>
        private const double UpdatePeriodDays = 1;

        #endregion

        #region Public Methods and Operators

        /// <summary>
        /// The check update if enabled.
        /// </summary>
        public static void CheckUpdateIfEnabled()
        {
            if (Settings.Default.FirstRun)
            {
                Settings.Default.FirstRun = false;
                ShowPrivacyDialog();
            }
            else if (Settings.Default.AutoUpdate)
            {
                CheckUpdate();
            }

            /*else
            {
                // nothing to do
                // auto update is turn off
            }*/
        }

        #endregion

        #region Methods

        /// <summary>
        /// The check update.
        /// </summary>
        private static void CheckUpdate()
        {
            if (!IsItTimeToCheckUpdate())
            {
                return;
            }

            Settings.Default.AutoUpdateLastCheck = DateTime.Now;
            string page;
            try
            {
                page = SimpleHttp.RequestPage("http://s.3po.ru/conusic/update.ini");
            }
            catch (Exception)
            {
                return;
            }

            Match match;
            if (!(match = Regex.Match(page, "version=([.0-9]*)")).Success)
            {
                return;
            }

            var avaliableVersion = new Version(match.Groups[1].ToString());
            var applicationVersion = Assembly.GetEntryAssembly().GetName().Version;

            if (avaliableVersion > applicationVersion)
            {
                if (File.Exists("updateConusic.exe"))
                {
                    Process.Start("updateConusic.exe");
                    Environment.Exit(0);
                }
                else
                {
                    ErrorReport.Show(
                        new FileNotFoundException(
                            "Автообновление не найдено, перезагрузите программу с сайта http://3po.ru"));
                }
            }
        }

        /// <summary>
        /// The is it time to check update.
        /// </summary>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        private static bool IsItTimeToCheckUpdate()
        {
            var deltaTime = DateTime.Now - Settings.Default.AutoUpdateLastCheck;
            if (deltaTime.TotalDays > UpdatePeriodDays || deltaTime.TotalDays < 0)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// The show privacy dialog.
        /// </summary>
        private static void ShowPrivacyDialog()
        {
            DialogResult result = (new AutoUpdateFirstDialog()).ShowDialog();
            if (result == DialogResult.OK)
            {
                Settings.Default.AutoUpdate = true;
                CheckUpdate();
            }
            else
            {
                Settings.Default.AutoUpdate = false;
            }
        }

        #endregion
    }
}